import { Alert, Modal, Table, Form, Select, Input, TimePicker, message, Button, Descriptions, InputNumber, Checkbox, Rate } from 'antd';
import { connect } from 'umi';
import React, { useState, useEffect } from 'react';
import moment from 'moment';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import styles from './addSchedule.less'
import db from '@/utils/localstorage';
import { saveSchedule } from './service';
const format = 'HH:mm';
const layout = {
  labelCol: { span: 2 },
  wrapperCol: { span: 10 },
};

let oriData = [
  {
    key: 0,
  },
  {
    key: 1,
  },
  {
    key: 2,
  },
];
const AddSchedule = props => {
  const { dispatch, handleOk, handleCancel, coachList, courseList, siteList, location } = props;
  const { query } = location || {};
  const { weekList } = query || {};
  const [form] = Form.useForm();
  const [scheduleList, setScheduleList] = useState({});
  const [visible, setVisible] = useState(false);
  const [courseInfo, setCourseInfo] = useState({});
  const [courseInfoIndex, setCourseInfoIndex] = useState(null);
  useEffect(() => {
    if (dispatch) {
      dispatch({
        type: 'cubeSchedule/fetchCoach',
        payload: {
          empType: 2,
        },
      })
      dispatch({
        type: 'cubeSchedule/selectAllCourse',
        payload: {
          classType: '1'
        },
      })
      dispatch({
        type: 'cubeSchedule/fetchShopList',
        payload: {
          userId: db.get("user").userId
        }
      })
      dispatch({
        type: 'cubeSchedule/querySiteInfoListByVenueIdNotPage',
        payload: {
          id: db.get("venue").id,
          usePurpose: 4
        }
      })
    }
  }, []);
  const getCurrWeekDays = () => {
    let date = []
    const start = moment(weekList?.[0]).weekday(0).format('YYYY-MM-DD'); //本周一
    const end = moment(weekList?.[0]).weekday(6).format('YYYY-MM-DD'); //本周日
    date.push(start)
    date.push(end)
    return date
  }
  const getWeek = (date) => {
    let week = moment(date).day()
    switch (week) {
      case 1:
        return '星期一'
      case 2:
        return '星期二'
      case 3:
        return '星期三'
      case 4:
        return '星期四'
      case 5:
        return '星期五'
      case 6:
        return '星期六'
      case 0:
        return '星期日'
    }
  }
  const getColumns = () => {
    let date = getCurrWeekDays();
    var columns = [];
    for (var i = 0; i <= 6; i++) {
      if (i == 0) {
        columns.push({
          title: <>{getWeek(date[0])}<br />{moment(date[0]).format('MM月DD日')}</>,
          dataIndex: date[0],
          editable: true,
        });
      } else if (i == 6) {
        columns.push({
          title: <>{getWeek(date[1])}<br />{moment(date[1]).format('MM月DD日')}</>,
          dataIndex: date[1],
          editable: true,
        });
      } else {
        let day = moment(date[0]).add(i, 'days').format('YYYY-MM-DD')
        columns.push({
          title: <>{getWeek(day)}<br />{moment(day).format('MM月DD日')}</>,
          dataIndex: day,
          editable: true,
        })
      }
    }
    return columns;
  }

  const getData = () => {
    let date = getCurrWeekDays();
    var columns = [];
    oriData.map((item, index) => {
      if (index == item.key) {
        for (var i = 1; i <= 7; i++) {
          if (i == 1) {
            item[moment(date[0]).format('YYYY-MM-DD')] = ""
          } else if (i == 7) {
            item[moment(date[1]).format('YYYY-MM-DD')] = ""
          } else {
            item[moment(date[0]).add(i, 'days').format('YYYY-MM-DD')] = ""
          }
        }
      }
      return item
    })
    return oriData;
  }

  const columns = getColumns()

  /**
   * 课程选择
   * @param {*} dataIndex 
   */
  const onChangeCourse = (value, dataIndex) => {
    let course = {};
    if (value) {
      course = courseList?.find(item => item.id === value)
    }
    if (!!scheduleList[dataIndex]) {
      scheduleList[dataIndex]['courseId'] = course
      setScheduleList(scheduleList)
    } else {
      scheduleList[dataIndex] = {
        courseId: { ...course }
      }
      setScheduleList(scheduleList)
    }
  }

  /**
   * 教练选择
   * @param {*} dataIndex 
   */
  const onChangeCoach = (value, dataIndex) => {
    if (!!scheduleList[dataIndex]) {
      scheduleList[dataIndex]['coachId'] = value
      setScheduleList(scheduleList)
    } else {
      scheduleList[dataIndex] = {
        coachId: value
      }
      setScheduleList(scheduleList)
    }
  }

  /**
   * 场地选择
   * @param {*} dataIndex 
   */
  const onChangeSite = (value, dataIndex) => {
    if (!!scheduleList[dataIndex]) {
      scheduleList[dataIndex]['siteId'] = value
      setScheduleList(scheduleList)
    } else {
      scheduleList[dataIndex] = {
        siteId: value
      }
      setScheduleList(scheduleList)
    }
  }

  const EditableCell = ({
    editing,
    dataIndex,
    title,
    inputType,
    record,
    index,
    children,
    coachList,
    siteList,
    courseList,
    ...restProps
  }) => {
    let inputNode;
    if (record.key == 0) {

      inputNode = <Select style={{ width: 120 }} defaultValue={scheduleList[dataIndex] ? scheduleList[dataIndex].coachId : []} placeholder="请选择教练" dropdownMatchSelectWidth={false} onChange={(value) => onChangeCoach(value, dataIndex)} allowClear
        showSearch
        filterOption={(input, option) =>
          option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
        }>
        {
          coachList && coachList.map((item, index) => <Select.Option value={item.userId} key={index}>{item.name}</Select.Option>)
        }
      </Select>
    } else if (record.key == 1) {
      inputNode = <Select style={{ width: 120 }} defaultValue={scheduleList[dataIndex] ? scheduleList[dataIndex].siteId : []} placeholder="请选择场地" dropdownMatchSelectWidth={false} onChange={(value) => onChangeSite(value, dataIndex)} allowClear
        showSearch
        filterOption={(input, option) =>
          option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
        }
      >
        {
          siteList && siteList.map((item, index) => <Select.Option value={item.id} key={index}>{item.name}</Select.Option>)
        }
      </Select>
    }
    else if (record.key == 2) {
      inputNode = <>
        <Select style={{ width: 120 }} defaultValue={scheduleList[dataIndex] ? scheduleList[dataIndex].courseId?.id : []} placeholder="请选择课程" dropdownMatchSelectWidth={false} onChange={(value) => onChangeCourse(value, dataIndex)} allowClear
          showSearch
          filterOption={(input, option) =>
            option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
          }>
          {
            courseList && courseList.map((item, index) => <Select.Option value={item.id} key={index}>{item.courseName}</Select.Option>)
          }
        </Select>
        <div style={{ fontSize: 12, marginTop: 4, cursor: 'pointer', color: '#1890ff' }} onClick={() => {
          if (scheduleList[dataIndex]?.['courseId']) {
            setVisible(true)
            setCourseInfoIndex(dataIndex);
            setCourseInfo(scheduleList[dataIndex]?.['courseId'] ?? {})
          } else {
            message.warn('请先选择课程');
            return;
          }
        }}>课程属性配置</div>
      </>
    }
    else {
      <Input />
    }
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item
            name={dataIndex}
            style={{
              margin: 0,
            }}
          >
            {inputNode}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };

  const mergedColumns = columns.map(col => {
    if (!col.editable) {
      return col;
    }

    return {
      ...col,
      onCell: record => ({
        record,
        inputType: 'select',
        dataIndex: col.dataIndex,
        title: col.title,
        index: col.index,
        editing: true,
        coachList: coachList,
        siteList: siteList,
        courseList: courseList,
      }),
    };
  });

  const handleScheduleOk = async () => {
    const fieldsValue = await form.validateFields();
    //form value 是数组的必填字段
    let paramsArray = [];
    for (let key in scheduleList) {
      let params = {
        date: key,
        venueId: fieldsValue.venueId,
        openingTime: moment(fieldsValue.time).format('mm'),
        openingTimeHour: moment(fieldsValue.time).format('HH')
      }
      if (scheduleList[key]) {
        for (let _key in scheduleList[key]) {
          console.log('scheduleList[key]>>>',scheduleList[key])
          if (_key === 'courseId') {
            params['courseId'] = scheduleList[key]['courseId']['id']
            params['onceCardCoefficient'] = scheduleList[key]['courseId']['onceCardCoefficient']
            params['courseDuration'] = scheduleList[key]['courseId']['courseDuration']
            params['maximumAttendance'] = scheduleList[key]['courseId']['maximumAttendance']
            params['isStartUpClass'] = scheduleList[key]['courseId']['isStartUpClass']
            params['minimumNumberClasses'] = scheduleList[key]['courseId']['minimumNumberClasses']
            params['difficulty'] = scheduleList[key]['courseId']['difficulty']
            params['sellPrice'] = scheduleList[key]['courseId']['sellPrice']
          } else {
            params[_key] = scheduleList[key][_key]
          }
        }
      }
      paramsArray.push(params)
    }
    const hide = message.loading('正在添加');
    try {
      let result = await saveSchedule(paramsArray);
      hide();
      if (result.code == 0) {
        message.success('添加成功，即将跳转');
        setVisible(false)
        window.history.back();
        return true;
      } else {
        message.error(result.message);
        return false;
      }
    } catch (error) {
      console.log('error>>>',error)
      hide();
      message.error('添加失败，请重试');
      return false;
    }
  }

  const handleChangeInfo = (name, value) => {
    const _courseInfo = { ...courseInfo };
    const _scheduleList = { ...scheduleList };
    _courseInfo[name] = value;
    setCourseInfo(_courseInfo);
    if (_scheduleList[courseInfoIndex] && _scheduleList[courseInfoIndex]['courseId']) {
      _scheduleList[courseInfoIndex]['courseId'] = _courseInfo;
      setScheduleList(_scheduleList)
    }
  }
  return (
    <PageHeaderWrapper>
      <div style={{ background: '#FFFFFF', padding: 10 }}>
        <Alert message="注：排期时课时所支持的会员卡、课时费类型、最少开课人数，将同步课程相关设置，排期后此类设置项将不随课程设置项的修改而变动" type="info" showIcon style={{ fontSize: 12 }} />
        <br />
        <Form
          {...layout}
          name="basic"
          form={form}
        >
          {/* <Form.Item
                label="选择场馆"
                name="venueId"
                rules={[{ required: true, message: '请选择场馆' }]}
              >
                <Select style={{ width: '100%' }} placeholder="请选择" onChange={venueChange}>
                    {
                        shopList&&shopList.map((item,index)=> <Select.Option value={item.id} key={index}>{item.name}</Select.Option>)
                    }
                </Select>
              </Form.Item> */}
          <Form.Item
            label="开课时间"
            name="time"
            rules={[{ required: true, message: '请选择开课时间' }]}
          >
            <TimePicker format={format} />
          </Form.Item>
        </Form>
        <Table
          rowKey="id"
          bordered
          components={{
            body: {
              cell: EditableCell,
            },
          }}
          dataSource={getData()}
          columns={mergedColumns}
          pagination={false}
        />
      </div>
      <div style={{ marginTop: 20, display: 'flex', justifyContent: 'center' }}>
        <Button type="primary" onClick={handleScheduleOk}>
          提交
        </Button>
        <Button
          style={{
            marginLeft: 8,
          }}
          onClick={() => window.history.back()}
        >
          返回
        </Button>
      </div>
      {
        visible && (
          <Modal title="课程属性" visible={visible} width={800}
            footer={<Button onClick={() => {
              setVisible(false);
              setCourseInfoIndex(null);
              setCourseInfo({})
            }}>取消</Button>}
            onCancel={()=>{
              setVisible(false);
              setCourseInfoIndex(null);
              setCourseInfo({})
            }}>
            <Descriptions column={2} className={styles.infoWrap}>
              <Descriptions.Item label="次卡扣卡系数"><InputNumber min={0} value={courseInfo?.onceCardCoefficient || 1} onChange={(value) => handleChangeInfo('onceCardCoefficient', value)} /></Descriptions.Item>
              <Descriptions.Item label="课程时长(分钟)"><InputNumber min={0} value={courseInfo?.courseDuration} onChange={(value) => handleChangeInfo('courseDuration', value)} /></Descriptions.Item>
              <Descriptions.Item label="最多上课人数"><InputNumber min={0} value={courseInfo?.maximumAttendance} onChange={(value) => handleChangeInfo('maximumAttendance', value)} /></Descriptions.Item>
              <Descriptions.Item label="人数不足不开课"><Checkbox checked={courseInfo?.isStartUpClass} onChange={(e) => {
                const value = e.target.value;
                handleChangeInfo('isStartUpClass', value ? '1' : '0')
              }}>是</Checkbox ></Descriptions.Item>
              <Descriptions.Item label="最少开课人数"><InputNumber min={0} value={courseInfo?.minimumNumberClasses} onChange={(value) => handleChangeInfo('minimumNumberClasses', value)} /></Descriptions.Item>
              <Descriptions.Item label="难易度" style={{ display: 'flex', alignItems: 'center' }}><Rate value={courseInfo?.difficulty} onChange={(value) => handleChangeInfo('difficulty', value)} /></Descriptions.Item>
              <Descriptions.Item label="售价"><InputNumber min={0} value={courseInfo?.sellPrice} onChange={(value) => handleChangeInfo('sellPrice', value)} /></Descriptions.Item>
            </Descriptions>
          </Modal>
        )
      }
    </PageHeaderWrapper>
  );
};

export default connect(({ loading, cubeSchedule }) => ({
  shopList: cubeSchedule.shopList,
  coachList: cubeSchedule.coachList,
  siteList: cubeSchedule.siteList,
  courseList: cubeSchedule.courseList,
  submitting: loading.effects['cubeSchedule/add'],
}))(AddSchedule);

